<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/13
 * Time: 9:56
 */

namespace App\Http\Controllers\Doctor;

use App\Http\Controllers\ApiController;
use App\LogicService\Contracts\DicTagLogicContract;
use App\LogicService\Contracts\HospitalManageLogicContract;
use App\Models\Doctor;
use App\Models\Hospital;
use App\Models\PatientDetail;
use App\Models\Reservation\Ability;
use App\Models\UserBase;
use App\Models\SceneManage;
use Illuminate\Http\Request;

class ManageController extends ApiController
{

    protected $request;

    protected $hospitalManage;

    protected $dicTag;

    public $stHospitalModel;
    public $stUserBaseModel;
    public $stHospitalManageModel;


    public function __construct(Request $request, HospitalManageLogicContract $hospitalManage, DicTagLogicContract $dicTag)
    {
        parent::__construct();
        $this->request = $request;
        $this->hospitalManage = $hospitalManage;
        $this->dicTag = $dicTag;

        $this->stHospitalModel = new Hospital();
        $this->stUserBaseModel = new UserBase();
        $this->stHospitalManageModel = new SceneManage();
    }


    //用户列表
    public function getList()
    {

        $size = $this->request->get('size') ?: 20;
        $user = \Auth::user();
        //$user = User::where('phone','13090908778')->first();
        $type = $this->request->get('type');// 类型

        $phone = $this->request->get('phone');// 手机号

        $name = $this->request->get('name');// 姓名

        $hospitalId = $this->request->get('hospital_id');// 医院ID

        $where = [];

        if (in_array($type, ['0', '1', '2', '3', '4'], true)) {
            $where[] = ['type', '=', $type];
        }

        if (!empty($phone)) {
            $where[] = ['phone', '=', $phone];
        }
        if (!empty($name)) {
            $where[] = ['name', '=', $name];
        }
        if (!empty($hospitalId)) {
            $where[] = ['hospital_id', '=', $hospitalId];
        }
        /*根据用户类型，决定列表看到的类型
         * 0：系统-》全部
         * 1：患者-》无
         * 2：医生-》自己的--病人
         * 3：医院管理员-》所属医院的--医生
         * 4：区域管理员-》所管理的医院的--医院管理员，医生
         * */
        $userType = $user->type;
        $inType = [];
        switch ($userType) {
            case 0:
                $inType = ['0', '1', '2', '3', '4'];
                break;
            case 2:
                $inType = ['1'];
                break;
            case 3:
                $inType = ['2'];
                break;
            case 4:
                $inType = ['2', '3'];
                break;
        }

        // =====
        if ($user->isAdmin()) {
            $user_list = UserBase::where($where)
                ->whereIn('type', $inType)
                ->orderBy('id', 'desc')
                ->paginate($size)
                ->toArray();
        } else {
            $hospital_ids[] = $user->hospital_id;
            if ($user->isRegionAdmin()) {
                //区域管理员
                $hospitalManage = $this->hospitalManage->show($user->account);
                $hospital_ids = json_decode($hospitalManage->hospital_ids);
                $hospital_ids[] = $user->hospital_id;
            }

            $user_list = UserBase::whereIn('hospital_id', $hospital_ids)
                ->where($where)
                ->orderBy('id', 'desc')
                ->whereIn('type', $inType)
                ->paginate($size)
                ->toArray();
        }
        // =====


        return $this->response($user_list);
    }

    // 添加用户-tds
    public function store()
    {

        $this->validate($this->request, [
            'hospital_ids' => 'string',
            'phone' => 'required|string',
            'password ' => 'string',
            'type' => 'required|integer',
            'ISSHOWMOBILE' => 'integer',
            'name' => 'string|required',

            'JOB' => 'string',
            'SKILLED' => 'string',
            'DESC' => 'string',
            'TAG' => 'string',

            //医生或者公用
            'PIC' => 'string',

            'sex' => 'integer',
            'DIABETESTYPE' => 'integer',//糖尿病类型
            'ILLYEARS' => 'string',//确诊时间
            'TREATTYPE' => 'string',//治疗方式
            'HEARTRATE' => 'integer',//心率
            'BMI' => 'string',
            'HEIGHT' => 'numeric',
            'WEIGHT' => 'numeric',
            'WAISTLINE' => 'integer',
            'HIGHESTHYPERTENSION' => 'integer',
            'LOWESTHYPERTENSION' => 'integer',

        ]);


        //用户表
        $account = time() . rand(100, 999);
        $phone = $this->request->input('phone');
        $DEVICET = 2;
        $password = md5($this->request->input('password'));
        $type = $this->request->input('type');
        $hospital_id = $this->request->input('hospital_id');
        $ISSHOWMOBILE = $this->request->input('ISSHOWMOBILE');
        $name = $this->request->input('name');
        $sex = $this->request->input('sex');
        if ($type != 1) {
            $this->validate($this->request, [
                'hospital_id' => 'required|integer',
            ]);
        }
        if ($type == 1) {
            $input['password'] = md5($this->getmd5($this->request->input('password')));
        }

        //根据手机号判断用户是否存在
        $is_user = UserBase::where('phone', $phone)->first();

        if ($is_user) {
            return $this->setMessage('手机号已经注册过')->setCode('400004')->response();
        }


        //保存用户信息到用户表
        $user_base = New UserBase();
        $user_base->phone = $phone;
        $user_base->account = $account;
        $user_base->DEVICET = $DEVICET;
        $user_base->type = $type;
        $user_base->sex = $sex;
        $user_base->password = $password;
        $user_base->hospital_id = $hospital_id;
        $user_base->ISSHOWMOBILE = $ISSHOWMOBILE;
        $user_base->name = $name;
        $user_base->pic_type = 1;
        $user_detail = $user_base->save();

        if ($user_detail) {
            //保存医生到医生表
            if ($type == 2 || $type == 3 || $type == 4) {


                //医生表
                $JOB = $this->request->input('JOB');
                $SKILLED = $this->request->input('SKILLED');
                $DESC = $this->request->input('DESC');
                $TAG = $this->request->input('TAG');
                $PIC = $this->request->input('PIC');


                $doctor = New Doctor();
                $doctor->ACCOUNT = $account;
                $doctor->SKILLED = $SKILLED;
                $doctor->JOB = $JOB;
                $doctor->DESC = $DESC;
                $doctor->TAG = $TAG;
                $doctor->PIC = $PIC;
                $doctor->save();


            }
            //保存患者到患者表
            if ($type == 1) {


                $DIABETESTYPE = $this->request->input('DIABETESTYPE');
                $ILLYEARS = $this->request->input('ILLYEARS');
                $TREATTYPE = $this->request->input('TREATTYPE');
                $HEARTRATE = $this->request->input('HEARTRATE');
                $BMI = $this->request->input('BMI');
                $HEIGHT = $this->request->input('HEIGHT');
                $WEIGHT = $this->request->input('WEIGHT');
                $WAISTLINE = $this->request->input('WAISTLINE');
                $HIGHESTHYPERTENSION = $this->request->input('HIGHESTHYPERTENSION');
                $LOWESTHYPERTENSION = $this->request->input('LOWESTHYPERTENSION');
                $PIC = $this->request->input('PIC');


                $patient = new PatientDetail();
                $patient->ACCOUNT = $account;
                $patient->DIABETESTYPE = $DIABETESTYPE;
                $patient->ILLYEARS = $ILLYEARS;
                $patient->TREATTYPE = $TREATTYPE;
                $patient->HEARTRATE = $HEARTRATE;
                $patient->BMI = $BMI;
                $patient->HEIGHT = $HEIGHT;
                $patient->WEIGHT = $WEIGHT;
                $patient->WAISTLINE = $WAISTLINE;
                $patient->HIGHESTHYPERTENSION = $HIGHESTHYPERTENSION;
                $patient->LOWESTHYPERTENSION = $LOWESTHYPERTENSION;
                $patient->PIC = $PIC;
                $patient->save();


            }
            //保存区域医院到区域管理表
            if ($type == 4) {
                //区域管理员表
                $hospital_ids = json_encode(explode(",", $this->request->input('hospital_ids')));
                $sceneManage = new SceneManage();
                $sceneManage->account = $account;
                $sceneManage->hospital_ids = $hospital_ids;
                $sceneManage->save();
            }

        }

        return $this->setMessage('添加成功')->setCode('10000')->response();
    }


    public function edit()
    {

        $this->validate($this->request, [
            'user_id' => 'integer|required',
            'hospital_ids' => 'string',
            'phone' => 'string',
            'password ' => 'string',
            'type' => 'required|integer',
            'hospital_id' => 'integer',
            'ISSHOWMOBILE' => 'integer',
            'name' => 'required',

            'JOB' => 'string',
            'SKILLED' => 'string',
            'DESC' => 'string',
            'TAG' => 'string',

            //医生或者公用
            'PIC' => 'string',

            'sex' => 'integer',
            'DIABETESTYPE' => 'integer',//糖尿病类型
            'ILLYEARS' => 'string',//确诊时间
            'TREATTYPE' => 'string',//治疗方式
            'HEARTRATE' => 'integer',//心率
            'BMI' => 'string',
            'HEIGHT' => 'numeric',
            'WEIGHT' => 'numeric',
            'WAISTLINE' => 'integer',
            'HIGHESTHYPERTENSION' => 'integer',
            'LOWESTHYPERTENSION' => 'integer',

        ]);


        //用户表

        $type = $this->request->input('type');
        $user_id = $this->request->input('user_id');


        //根据手机号判断用户是否存在
        $user_base = UserBase::where('id', $user_id)->first();

        if (!$user_base) {
            return $this->setMessage('用户不存在')->setCode('400004')->response();
        }

        //保存用户信息到用户表

        $input = $this->request->input();
        $password = $this->request->input('password');
        if (!empty($password)) {
            $input['password'] = md5($this->request->input('password'));
            if ($type == 1) {
                $input['password'] = md5($this->getmd5($this->request->input('password')));
            }
        } else {
            unset($input['password']);
        }
        $input['pic_type'] = 1;

        $user_detail = $user_base->fill($input)->save();

        if ($user_detail) {
            //保存医生到医生表
            if ($type == 2 || $type == 3 || $type == 4) {

                $doctor = Doctor::where('ACCOUNT', $user_base->account)->first()->fill($this->request->input())->save();
            }
            //保存患者到患者表
            if ($type == 1) {

                $patient = PatientDetail::where('ACCOUNT', $user_base->account)->first()->fill($this->request->input())->save();

            }
            //保存区域医院到区域管理表
            if ($type == 4) {
                //区域管理员表
                $hospital_ids = json_encode(explode(",", $this->request->input('hospital_ids')));
                $sceneManage = SceneManage::firstOrNew(['account' => $user_base->account]);
                $sceneManage->hospital_ids = $hospital_ids;
                $sceneManage->save();
            }

        }

        return $this->setMessage('修改成功')->setCode('10000')->response();

    }

    /* tds-获取医院列表（添加用户->选择医院,）*/
    public function getHospitalList()
    {
        $typeValue = $this->request->input('type');
        //根据用户类型  获取医院列表
        $user = \Auth::user();
        //如果登录的是西医的管理员账户，那么在病历列表筛选的时候，只能筛选西医的医院
        $hospital_type = $user->hospital->type;
        if(!empty($typeValue)){
            $hospitals = Hospital::whereIsdel(0)->where('type',$hospital_type)->select('id', 'name', 'type')->get()->toArray();

        }else{
            $hospitals = Hospital::whereIsdel(0)->select('id', 'name', 'type')->get()->toArray();

        }
        //返回所有医院

        if ($user->isRegionAdmin()) {
            //区域管理员
            $hospitalManage = $this->hospitalManage->show($user->account);
            $hospital_ids = json_decode($hospitalManage->hospital_ids);
            $hospital_ids[] = $user->hospital_id;

            $hospitals = Hospital::whereIn('id', $hospital_ids)
                ->select('id', 'name', 'type')
                ->whereIsdel(0)
                ->orderBy('id', 'desc')
                ->get()
                ->toArray();

        }
        if ($user->isDoctorsAdmin()) {
            $hospital_ids[] = $user->hospital_id;

            $hospitals = Hospital::whereIn('id', $hospital_ids)
                ->select('id', 'name', 'type')
                ->whereIsdel(0)
                ->orderBy('id', 'desc')
                ->get()
                ->toArray();
        }

        return $this->response($hospitals);
    }

    /* tds-管理医院 选择 */
    public function getHospitalPageList()
    {
        /* 1西医（默认），2中医，3中西医
         * 中西医-》中医，中西医
         * 中医-》中医，中西医
         * 西医-》西医
         * */
        $size = $this->request->get('size', 5);
        //根据用户类型  获取医院列表
        $user = \Auth::user();
        if (!$user->isAdmin()) {
            return response(['code' => -20000, 'message' => '没有权限', 'data' => []]);
        }

        $userId = $this->request->get('user_id');// 1.从用户列表进入修改时，用户ID
        $hospitalId = $this->request->get('hospital_id');// 2.添加用户时，所属医院
        $hospitalId =  !empty($hospitalId) ?  $hospitalId : $this->stUserBaseModel->getHospitalIdByUserId($userId);
        $hospitalType = $this->stHospitalModel->getTypeByHospitalId($hospitalId);
        if ($hospitalType === 1) {
            $hospitals = Hospital::select('id', 'name', 'type')
                ->where('type', $hospitalType)
                ->paginate($size)
                ->toArray();
        } else {
            $hospitals = Hospital::select('id', 'name', 'type')
                ->whereIn('type', [2, 3])
                ->paginate($size)
                ->toArray();
        }


        return $this->response($hospitals);
    }

    public function searchHospitalList()
    {

        $this->validate($this->request, [
            'key' => 'required|string',

        ]);

        $key = $this->request->input('key');
        $size = $this->request->get('size') ?: 5;

        $hospitals = Hospital::whereIsdel(0)
            ->where('name', 'like', '%' . $key . '%')
            ->select('id', 'name', 'type')
            ->paginate($size)
            ->toArray();
        //返回所有医院


        return $this->response($hospitals);
    }

    /* 显示用户信息 */
    public function show()
    {
        $this->validate($this->request, [
            'user_id' => 'required|integer',
        ]);

        $user_id = $this->request->input('user_id');

        $user = UserBase::find($user_id);
        if (!$user) {
            return $this->setMessage('用户不存在')->setCode('400004')->response();
        }

        if ($user->type == 2 || $user->type == 3 || $user->type == 4) {

            $user->detail;
        }
        if ($user->type == 1) {
            $user->patient;
        }
        if ($user->type == 4) {
            $user->hospitals;
        }

        return $this->response($user->toArray());
    }


    public function getTagList()
    {
        $dicList = $this->dicTag->getList();
        return $this->response($dicList);
    }

    /* tds-页面 url:manage/user/index 用户管理列表页 */
    public function index()
    {
        $user = \Auth::user();

        // tds 平台和区域 添加医院筛选
        $selectHospitals = [];
        $selectArr = ['id', 'name'];
        $where = ['isdel' => 0];
        if ($user->isAn('admin')) {
//            $hospitals = Ability::find(1)->hospitals;// todo tds
            $selectHospitals = $this->stHospitalModel->select($selectArr)
                ->where($where)->get()->toArray();
        } else if ($user->isRegionAdmin()) {
            $account = $user->account;
            $manageHospitals = $this->stHospitalManageModel->select('hospital_ids')
                ->where('account', $account)->first()->toArray();
            $selectHospitals = $this->stHospitalModel->select($selectArr)
                ->where($where)
                ->whereIn('id', json_decode($manageHospitals['hospital_ids']))
                ->get()->toArray();
        }

        return view('reservation.user', compact('user', 'selectHospitals'));
    }


    //处理和Java md5加密不一致问题
    public function getmd5($p)
    {
        $p = md5($p, true);
        $bytes = array();
        for ($i = 0; $i < strlen($p); $i++) {
            $bytes[] = ord($p[$i]);
        }
        $m = "";
        for ($i = 0; $i < count($bytes); $i++) {
            $m .= (int)($bytes[$i] & 0x11);
        }
        return $m;
    }


    public function test()
    {
        $data['count'] = 400;
        $data['total'] = 20;

        return $this->responseData(40000,'成功',$data);
    }
}